﻿using Microsoft.Extensions.Configuration;
using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
using Spectre.Console;
using System.Diagnostics;
using WorkTool.Helpers;

namespace WorkTool
{
    public class PDFMerge : ITools
    {
        public void ToolsMethod(IConfigurationRoot config)
        {
            List<string> pdfFiles;
            while (true)
            {
                var directoryLine = AnsiConsole.Ask<string>("[bold][green1]请输入要合并的PDF文件夹（输入 n 取消）：[/] [/]");
                if (directoryLine.ToLower().Trim() == "n")
                    return;
                if (Directory.Exists(directoryLine))
                {
                    var files = Directory.GetFiles(directoryLine);
                    pdfFiles = files.Where(x => Path.GetExtension(x).Equals(".pdf")).ToList();
                    if (pdfFiles.Count > 1)
                        break;
                    AnsiConsole.MarkupLine($"[yellow]PDF文件夹内{(pdfFiles.Count == 0 ? "未找到.pdf文件" : "只存在一个.pdf文件，无需合并")}，请重新输入！[/]");
                }
                else
                {
                    AnsiConsole.MarkupLine("[yellow]PDF文件夹不存在，请重新输入！[/]");
                }
            }
            var filePath = Path.Combine(SettingsHelper._fileSettings.SaveFolder, $"Merge-{DateTime.Now:yyyyMMddHHmmss}.pdf");
            QuestPDF.Settings.License = LicenseType.Community;
            var pdf = DocumentOperation
                .LoadFile(pdfFiles[0]);
            for (int i = 1; i < pdfFiles.Count; i++)
            {
                pdf.MergeFile(pdfFiles[i]);
            }
            pdf.Save(filePath);
            AnsiConsole.MarkupLine($"[green1]文件已保存至\n[/] [bold][aqua]{filePath}[/][/]");
            Process.Start(new ProcessStartInfo
            {
                FileName = filePath,
                UseShellExecute = true
            });
            AnsiConsole.MarkupLine("[grey]按任意键继续...[/]");
            Console.ReadKey();
        }
    }
}